package website.haicheng.cloudgateway.filters;

import cn.hutool.json.JSONUtil;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.JwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import website.haicheng.cloudgateway.properties.IgnoreUrlProperties;
import website.haicheng.core.base.Resp;
import website.haicheng.core.constant.RedisPrefix;
import website.haicheng.core.util.JWTUtil;

/**
 * @description:
 * @author: 582895699@qq.com
 * @time: 2021/2/19 下午 01:25
 */
@Slf4j
@Component
public class TokenFilter implements GlobalFilter, Ordered {

    public static final String SEPARATE = ":";

    @Autowired
    private IgnoreUrlProperties urlProperties;

    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String requestPath = exchange.getRequest().getURI().getPath();
        if (urlProperties.getUrls().contains(requestPath)) {
            return chain.filter(exchange);
        }
        String token = getToken(exchange);
        String tokenFromRedis = redisTemplate.opsForValue().get(RedisPrefix.AUTH_MODULE_PREFIX + SEPARATE + token);
        if (StringUtils.isEmpty(token) || StringUtils.isEmpty(tokenFromRedis)) {
            return authResponse(exchange, HttpStatus.UNAUTHORIZED, "未登陆");
        }
        try {
            JWTUtil.parseToken(token);
        } catch (JwtException e) {
            log.warn("token错误;token:{}; JwtException:{}", token, e.getMessage());
            if (e instanceof ExpiredJwtException) {
                return authResponse(exchange, HttpStatus.OK, "token已失效");
            }
            return authResponse(exchange, HttpStatus.OK, "token错误");
        }
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * 从header中获取token
     *
     * @param exchange
     * @return
     */
    private String getToken(ServerWebExchange exchange) {
        HttpHeaders headers = exchange.getRequest().getHeaders();
        return headers.get("Authorization").get(0).replace("Bearer ", "");
    }

    private Mono<Void> authResponse(ServerWebExchange exchange, HttpStatus httpStatus, String message) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().setContentType(MediaType.APPLICATION_JSON_UTF8);
        response.setStatusCode(httpStatus);

        return response.writeWith(Mono.fromSupplier(() -> {
            DataBufferFactory bufferFactory = response.bufferFactory();
            return bufferFactory.wrap(JSONUtil.toJsonStr(Resp.error(httpStatus.value(), message)).getBytes());
        }));
    }
}
